// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
use anyhow::{anyhow};
use std::path::{self, Path};
use crate::*;
use std::fs::File;
use std::io::{BufRead, BufReader};
use reqwest::header::HeaderMap;
use tracing::{error, info, debug};
use std::sync::Arc;
type SharedState = Arc<Shared>;

#[tauri::command]
pub async fn async_get_last_png(state: tauri::State<'_, SharedState>, name: &str) -> Result<String,String> {   
    // State抽取案例，异步支持！
    debug!("greet command, state.startup = {:?} ...", state.startup);  
    let servers = ["8.155.160.209:9995", "www.mark.lengsh.cn:9995"];
    let last_png = 
        match get_tradedays_from_yee(servers[0]).await {
            Err(er) =>{
                debug!("get_tradedays_from_yee error: {}", er);
                format!("/public/{}.png", name)
            },
            Ok(mut days) =>{
                days.sort();
                format!("http://{}/yee/static/{}/{}.png", servers[0], days[days.len()-1], name)
            }
        };        
    Ok(last_png)
}
/**
 * server: 8.155.160.209:9995, www.mark.lengsh.cn:[9995, 9994],
 */
pub async fn get_tradedays_from_yee(server: &str) -> anyhow::Result< Vec<String> > {        
    let client = reqwest::Client::new();
    
    let api = if server.starts_with("http") {
            format!("{}/yee/api/tradedays", server)
        }else{
            format!("http://{}/yee/api/tradedays", server)
        };
        
    let mut headers = HeaderMap::new();
    // headers.insert("Authorization", "Bearer xman".parse()?);
    headers.insert("Content-Type", "application/json; charset=utf-8".parse()?);

    let r:Vec<String> = client
        .get(&api)
        .headers(headers)        
        .send()
        .await?
        .json()
        .await?;
    // debug!("{:#?}", r);
    return Ok(r);
}
